import { useMemberStore } from "@/stores"

//配置基地址
const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
//请求拦截器
uni.addInterceptor('request', {
  //拦截前触发
  invoke(args: UniApp.RequestOptions) {
    //请求接口不是http开头就拼接
    if (!args.url.startsWith('http')) {
      args.url = baseURL + args.url
    }
    //配置超时时间
    args.timeout = 50000
    //配置请求头
    args.header = {
      'source-client': 'miniapp',
      ...args.header
    }
    //获取token
    const store = useMemberStore()
    const token = store.profile?.token
    if (token) {
      args.header.Authorization = token
    }
  }
})

//文件上传
uni.addInterceptor('uploadFile', {
  //拦截前触发
  invoke(args: UniApp.RequestOptions) {
    //请求接口不是http开头就拼接
    if (!args.url.startsWith('http')) {
      args.url = baseURL + args.url
    }
    //配置超时时间
    args.timeout = 10000
    //配置请求头
    args.header = {
      'source-client': 'miniapp',
      ...args.header
    }
    //获取token
    const store = useMemberStore()
    const token = store.profile?.token
    if (token) {
      args.header.Authorization = token
    }
  }
})
//请求函数类型定义
type ResDataType<T> = {
  code: string
  msg: string
  result: T
}
//请求工具函数封装
export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<ResDataType<T>>((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        console.log(res);
        //请求成功
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as ResDataType<T>)
        } else if (res.statusCode === 401) {
          //401错误处理:清空会员信息，跳转登录页面
          const store = useMemberStore()
          store.clearProfile()
          uni.navigateTo({
            url: '/pages/login/login'
          })
        } else {
          //其他错误
          uni.showToast({
            title: (res.data as ResDataType<T>).msg,
            icon: 'none'
          })
          reject(res)
        }

      },
      fail: (err) => {
        uni.showToast({
          title: '请求失败',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}